/**
 * 导入仓库 url方式
 * @param type 默认normal, retry：重新导入
 * @param projectInfo 默认为null，默认数据，在重新导入时用到
 * @param retryCallback 重新导入成功的回调
 */

import React from 'react';
import PropTypes from 'prop-types';
import { Dialog } from '@teamix/ui';
import ChooseWays from './chooseWays';
import UrlForm from './url';
import SVNForm from './svn';
import PrivateGitLabForm from './privateGitLab';
import AliyunForm from './aliyun';
import GiteeForm from './gitee';
import ImportLocally from './ImportLocally';
import utils from 'utils';
import { getFeature } from 'utils/features';
import track, { enterModal } from 'utils/track';
import './index.scss';
import intl from '../../locale';

const PUBLIC_KEY =
  'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCNe7wKpTaYIdzrhoNXJ0YEFj+NF/o0MMRbixhXLJLq5c44xumOSBS5W8cgwlHwWkyPJs2B6byWsK3oYm6h/gIOS/LPCAaBpjiGw0GXSV4K7LAgZIP/T95J+prcTV2L86DtiH7CcWNGL9TlC4ATGi8fL7Elk+crkRHz9D9d6UGPPQIDAQAB';

const trackMap = {
  PRIVATE_GITLAB: {
    chooseWay: {
      action: 'import_repo',
      page: 'Dialog-ImportRepo',
      type: 'import self-built gitlab',
      control: '',
    },

    confirm: {
      action: 'confirm_button',
      page: 'Dialog-ImportRepo',
      type: 'import self-built gitlab',
      control: '',
    },
  },

  GITLAB: {
    chooseWay: {
      action: 'import_repo',
      page: 'Dialog-ImportRepo',
      type: 'import gitlab',
      control: '',
    },

    confirm: {
      action: 'confirm_button',
      page: 'Dialog-ImportRepo',
      type: 'import gitlab',
      control: '',
    },
  },

  GITHUB: {
    chooseWay: {
      action: 'import_repo',
      page: 'Dialog-ImportRepo',
      type: 'import github',
      control: '',
    },

    confirm: {
      action: 'confirm_button',
      page: 'Dialog-ImportRepo',
      type: 'import gitlab',
      control: '',
    },
  },

  ALIYUN: {
    chooseWay: {
      action: 'import_repo',
      page: 'Dialog-ImportRepo',
      type: 'import code.aliyun',
      control: '',
    },

    confirm: {
      action: 'confirm_button',
      page: 'Dialog-ImportRepo',
      type: 'import code.aliyun',
      control: '',
    },
  },

  GITEE: {
    chooseWay: {
      action: 'import_repo',
      page: 'Dialog-ImportRepo',
      type: 'import gitee',
      control: '',
    },

    confirm: {
      action: 'confirm_button',
      page: 'Dialog-ImportRepo',
      type: 'import gitee',
      control: '',
    },
  },

  url: {
    chooseWay: {
      action: 'import_repo',
      page: 'Dialog-ImportRepo',
      type: 'import by URL',
      control: '',
    },

    confirm: {
      action: 'confirm_button',
      page: 'Dialog-ImportRepo',
      type: 'import by URL',
      control: '',
    },
  },

  SVN: {
    chooseWay: {
      action: 'import_repo',
      page: 'Dialog-ImportRepo',
      type: 'import by SVN',
      control: '',
    },

    confirm: {
      action: 'confirm_button',
      page: 'Dialog-ImportRepo',
      type: 'import by SVN',
      control: '',
    },
  },

  CODING: {
    chooseWay: {
      action: 'import_repo',
      page: 'Dialog-ImportRepo',
      type: 'import coding',
      control: '',
    },

    confirm: {
      action: 'confirm_button',
      page: 'Dialog-ImportRepo',
      type: 'import coding',
      control: '',
    },
  },
  IMPORTLOCALLY: {
    chooseWay: {
      action: '',
      page: '',
      type: '',
      control: '',
    },
    confirm: {
      action: '',
      page: '',
      type: '',
      control: '',
    },
  },
};

export default class ImportProjectByUrlModal extends React.Component {
  static propTypes = {
    defaultNamespaceId: PropTypes.string,
    trigger: PropTypes.element,
    closeModal: PropTypes.func,
    isModalOpen: PropTypes.bool,
    type: PropTypes.string,
    projectInfo: PropTypes.object,
    retryCallback: PropTypes.func,
  };

  static defaultProps = {
    defaultNamespaceId: '',
    trigger: null,
    closeModal: () => {},
    type: 'normal', // 默认为normal, retry为重新导入
    projectInfo: {
      import_url: '',
      id: '',
    },

    retryCallback: () => {},
  };

  constructor(props) {
    super(props);
    let defaultWay = '';
    const auto_bind = utils.getUrlSearchParam('auto_bind') || '';
    if (auto_bind === 'gitee') {
      defaultWay = 'GITEE';
    } else if (['aliyun', 'aliyun_ram'].includes(auto_bind)) {
      defaultWay = 'ALIYUN';
    } else {
      defaultWay = 'ALIYUN';
    }
    let activeWay;
    if (props.type === 'retry') {
      activeWay = props.projectInfo.import_from_svn ? 'SVN' : 'url';
    } else {
      activeWay = defaultWay;
    }
    if (getFeature('project.import.active_way.selected')) {
      activeWay = getFeature('project.import.active_way.selected');
    }
    this.state = {
      submitting: false,
      isModalOpen: false,
      // 默认自建gitLab
      activeWay,
      // activeName: '自建 GitLab',
    };
  }

  static getDerivedStateFromProps(props) {
    if (props.trigger) {
      return {};
    }
    return {
      isModalOpen: props.isModalOpen,
    };
  }

  componentDidMount() {
    enterModal('Dialog-ImportRepo', {
      sendPV: false,
      sendPerf: false,
    });
  }

  showModal = () => {
    this.setState({
      isModalOpen: true,
    });
  };

  onClose = () => {
    const auto_bind = utils.getUrlSearchParam('auto_bind') || '';
    this.setState({
      isModalOpen: false,
    });

    if (auto_bind) {
      window.history.replaceState({}, null, '/');
    }
    this.props.closeModal();
  };

  setSubmitting = (submitting) => {
    this.setState({
      submitting,
    });
  };

  handleSelectWay = (way) => {
    track(trackMap[way].chooseWay);
    this.setState({
      activeWay: way,
    });
  };

  renderToken = () => {
    return null;
  };

  handleOk = () => {
    track(trackMap[this.state.activeWay].confirm);
    // 获取子组件数据
    this.form.handleOk();
  };

  setDisabled = (disabled) => {
    this.setState({
      disabled,
    });
  };

  // 供子元素切换选项后强制更新dialog，否则会导致不出滚动条
  forceUpdateDialog = () => {};

  render() {
    const { type } = this.props;
    const { activeWay, submitting, disabled } = this.state;
    return (
      <React.Fragment>
        {this.state.isModalOpen ? (
          <Dialog
            title={intl.get({
              id: 'code-assets.components.importProjectModal.ImportCodeLibrary',
              defaultMessage: '导入代码库',
            })}
            shouldUpdatePosition
            visible
            style={{ width: '696px' }}
            onOk={this.handleOk}
            onCancel={this.onClose}
            onClose={this.onClose}
            okProps={{ loading: !!this.state.submitting, disabled }}
            className="import-project-modal"
            ref={(ref) => {
              this.dialog = ref;
            }}
            footer={activeWay !== 'IMPORTLOCALLY'}
          >
            <ChooseWays
              activeWay={activeWay}
              handleSelectWay={this.handleSelectWay}
              isRetry={type === 'retry'}
            />
            {activeWay === 'url' && (
              <UrlForm
                {...this.props}
                PUBLIC_KEY={PUBLIC_KEY}
                ref={(ref) => {
                  this.form = ref;
                }}
                submitting={submitting}
                setSubmitting={this.setSubmitting}
                onClose={this.onClose}
                setDisabled={this.setDisabled}
              />
            )}
            {activeWay === 'SVN' && (
              <SVNForm
                {...this.props}
                PUBLIC_KEY={PUBLIC_KEY}
                ref={(ref) => {
                  this.form = ref;
                }}
                submitting={submitting}
                setSubmitting={this.setSubmitting}
                onClose={this.onClose}
                setDisabled={this.setDisabled}
                forceUpdateDialog={this.forceUpdateDialog}
              />
            )}
            {activeWay === 'PRIVATE_GITLAB' && (
              <PrivateGitLabForm
                {...this.props}
                PUBLIC_KEY={PUBLIC_KEY}
                ref={(ref) => {
                  this.form = ref;
                }}
                submitting={submitting}
                setSubmitting={this.setSubmitting}
                onClose={this.onClose}
                setDisabled={this.setDisabled}
              />
            )}
            {activeWay === 'GITLAB' && (
              <PrivateGitLabForm
                {...this.props}
                PUBLIC_KEY={PUBLIC_KEY}
                ref={(ref) => {
                  this.form = ref;
                }}
                submitting={submitting}
                setSubmitting={this.setSubmitting}
                onClose={this.onClose}
                setDisabled={this.setDisabled}
                platform_type="GITLAB"
              />
            )}
            {activeWay === 'GITHUB' && (
              <PrivateGitLabForm
                {...this.props}
                PUBLIC_KEY={PUBLIC_KEY}
                ref={(ref) => {
                  this.form = ref;
                }}
                submitting={submitting}
                setSubmitting={this.setSubmitting}
                onClose={this.onClose}
                setDisabled={this.setDisabled}
                platform_type="GITHUB"
              />
            )}
            {activeWay === 'ALIYUN' && (
              <AliyunForm
                {...this.props}
                PUBLIC_KEY={PUBLIC_KEY}
                ref={(ref) => {
                  this.form = ref;
                }}
                submitting={submitting}
                setSubmitting={this.setSubmitting}
                onClose={this.onClose}
                setDisabled={this.setDisabled}
              />
            )}
            {activeWay === 'GITEE' && (
              <GiteeForm
                {...this.props}
                PUBLIC_KEY={PUBLIC_KEY}
                ref={(ref) => {
                  this.form = ref;
                }}
                submitting={submitting}
                setSubmitting={this.setSubmitting}
                onClose={this.onClose}
                setDisabled={this.setDisabled}
              />
            )}
            {activeWay === 'CODING' && (
              <PrivateGitLabForm
                {...this.props}
                PUBLIC_KEY={PUBLIC_KEY}
                ref={(ref) => {
                  this.form = ref;
                }}
                submitting={submitting}
                setSubmitting={this.setSubmitting}
                onClose={this.onClose}
                setDisabled={this.setDisabled}
                platform_type="CODING"
              />
            )}
            {activeWay === 'IMPORTLOCALLY' && (
              <ImportLocally
                {...this.props}
                PUBLIC_KEY={PUBLIC_KEY}
                ref={(ref) => {
                  this.form = ref;
                }}
                submitting={submitting}
                setSubmitting={this.setSubmitting}
                onClose={this.onClose}
                setDisabled={this.setDisabled}
                platform_type="IMPORTLOCALLY"
              />
            )}
          </Dialog>
        ) : null}
        {!!this.props.trigger &&
          React.cloneElement(this.props.trigger, {
            onClick: (e) => {
              this.props.trigger.props.onClick && this.props.trigger.props.onClick(e);
              this.showModal();
            },
          })}
      </React.Fragment>
    );
  }
}
